﻿using MediatR;
using Microsoft.AspNetCore.WebUtilities;
using RBAC_Uthorization.API.Application.Command.MenuCommand;
using RBAC_Uthorization.API.DTO;
using RBAC_Uthorization.API.Extensions;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Infrstructre.Impl;
using RBAC_Uthorization.Infrstructre.Interface;
using StackExchange.Redis;

namespace RBAC_Uthorization.API.Application.CommandHandlers.MenuHandler
{
    public class MenuDeleteCommandHandlers : IRequestHandler<MenuDeleteCommand, ApiResult<int>>
    {
        private readonly IMenuRepository _menuRepository;
        private readonly ILogger<MenuDeleteCommandHandlers> _logger;
        private readonly IFunctionRepository _functionRepository;
        private readonly IConfiguration _configuration;
        private readonly RedisConnectionService _redisConnectionService;
        private readonly IUserInfoRepository _userInfoRepository;
        private readonly IRoleMenuRepository _roleMenuRepository;
        private readonly IRoleMenuFuncRepository _roleMenuFuncRepository;


        public MenuDeleteCommandHandlers(ILogger<MenuDeleteCommandHandlers> logger, IMenuRepository menuRepository, IFunctionRepository functionRepository, IConfiguration configuration, RedisConnectionService redisConnectionService, IUserInfoRepository userInfoRepository, IRoleMenuRepository roleMenuRepository, IRoleMenuFuncRepository roleMenuFuncRepository)
        {
            _logger = logger;
            _menuRepository = menuRepository;
            _functionRepository = functionRepository;
            _configuration = configuration;
            _redisConnectionService = redisConnectionService;
            _userInfoRepository = userInfoRepository;
            _roleMenuRepository = roleMenuRepository;
            _roleMenuFuncRepository = roleMenuFuncRepository;
        }

        public async Task<ApiResult<int>> Handle(MenuDeleteCommand request, CancellationToken cancellationToken)
        {
            if (_configuration["Redis:Redisif"] == "1")
            {
                await _redisConnectionService.DeleteAsync($"MenuTree_{request.sys_id}");
                await _redisConnectionService.DeleteAsync($"Menu_{request.sys_id}");
            var userid = await _userInfoRepository.GetAllAsunc(u => u.sys_id == request.sys_id && u.del_flag == 0);
                await _redisConnectionService.DeleteAsync($"user:{userid}:{request.sys_id}:menuIds");
            }
            // 开启事务
            await _menuRepository.BeginTransactionAsync();
            {
                try
                {

                    foreach (var menuId in request.Id)
                    {
                        var menu = await _menuRepository.GetbyIdAsync(menuId);

                        if (menu == null)
                        {
                            return new ApiResult<int>(ResultCode.Error, "菜单不存在");
                        }
                        menu.del_flag = 1;
                        menu.update_by = request.UpdateName;
                        menu.update_date = DateTime.UtcNow;
                        await _menuRepository.UpdateAsync(menu);
                        var functions = await _functionRepository.GetAllAsunc(f => f.menu_id == menuId&&f.sys_id==request.sys_id&&f.del_flag==0);
                        foreach (var function in functions)
                        {
                            function.del_flag = 1;
                            function.update_by = request.UpdateName;
                            function.update_date = DateTime.UtcNow;
                            await _functionRepository.UpdateAsync(function);
                        }
                        var role= await _roleMenuRepository.GetAllAsunc(r => r.menu_id == menuId && r.del_flag == 0);
                        foreach (var item in role)
                        {
                            item.del_flag = 1;
                            item.update_by = request.UpdateName;
                            item.update_date = DateTime.UtcNow;
                            await _roleMenuRepository.UpdateAsync(item);
                        }
                        var roleMenuFunc = await _roleMenuFuncRepository.GetAllAsunc(r => r.menu_id == menuId && r.del_flag == 0);
                        foreach (var item in roleMenuFunc)
                        {
                            item.del_flag = 1;
                            item.update_by = request.UpdateName;
                            item.update_date = DateTime.UtcNow;
                            await _roleMenuFuncRepository.UpdateAsync(item);
                        }

                    }
                    await _menuRepository.CommitTransactionAsync();
                    _logger.LogInformation($"删除菜单成功,删除人:{request.UpdateName},删除菜单ID:{request.Id}");
                    return new ApiResult<int>();
                }
                catch (System.Exception ex)
                {
                    await _menuRepository.RollbackTransactionAsync();
                    _logger.LogError($"删除菜单失败:{ex.Message}->{ex.StackTrace}->{ex.InnerException}");
                    return new ApiResult<int>(ResultCode.Error, "删除菜单失败");
                }
            }
        }
    }

}
